const _ = require('../utils')

const noop = () => {}
const defaults = {
  title: '',
  content: '',
  showCancel: true,
  cancelText: '取消',
  cancelColor: '',
  confirmText: '确定',
  confirmColor: '',
  openType: '',
  prompt: false,
  value: '',
  placeholder: '',
  placeholderStyle: '',
  type: 'text',
  maxlength: 140,
  password: false,
  shown: false,
}

_.create('dialog', {
  properties: {
    title: String,
    content: String,
    showCancel: {
      type: Boolean,
      value: true,
    },
    cancelText: {
      type: String,
      value: '取消',
    },
    confirmText: {
      type: String,
      value: '确定',
    },
    openType: String,
  },

  data: {
    visibility: 'hidden',
    shown: false,
    inputValue: '',
    onConfirm: noop,
    onCancel: noop,
    onShow: noop,
    onHide: noop,
    onInput: noop,
  },

  methods: {
    close() {
      this.setData({ shown: false })
      this.data.onHide()
    },

    open(opts) {
      return new Promise((resolve, reject) => {
        const options = Object.assign({ position: 'center' }, defaults, opts, {
          onCancel: reject,
          onConfirm: resolve,
          shown: true,
        })

        this.setData(options)
      })
    },

    onCancel() {
      this.close()
      this.data.onCancel(new Error('userCancel'))
    },

    onConfirm(res) {
      if (this.data.prompt) {
        res.detail = { value: this.inputValue }
      }
      this.data.onConfirm(res)
    },

    onClick(e) {
      const { openType } = this.data

      if (
        openType === 'getPhoneNUmber' ||
        openType === 'getUserInfo' ||
        openType === 'launchApp' ||
        openType === 'openSetting'
      ) {
        return
      }
      this.onConfirm(e.detail)
    },

    onOpenSetting(e) {
      return this.onConfirm(e)
    },

    onInput(e) {
      const {
        detail: { value },
      } = e
      this.inputValue = value
      this.data.onInput(e)
    },

    message(opts) {
      return this.open(
        Object.assign(opts, {
          showCancel: false,
        })
      )
    },

    openSetting(opts, scope) {
      const options = Object.assign(opts, {
        openType: 'openSetting',
      })

      return this.open(options).then((res) => {
        if (!scope) return res
        const {
          detail: { authSetting },
        } = res
        return !authSetting[`scope.${scope}`]
          ? Promise.reject(new Error('userCancel'))
          : Promise.resolve(res)
      })
    },

    prompt(opts) {
      const options = Object.assign({ position: 'bottom' }, opts, { prompt: true })

      return this.open(options)
    },
  },
})
